﻿    using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;
using BaseDll;
using CommonTools;
using log4net;
using MotionIoLib;
using Sunny.UI;
using UserCtrl;
using System.Reflection;
namespace StationDemo
{
    public partial class StationForm : UIPage
    {
        private readonly Stationbase _stationBase;
        //整个IO列表
        Dictionary<string, IOMgr.IoDefine> m_dicInput;
        Dictionary<string, IOMgr.IoDefine> m_dicOutput;
        private Dictionary<string, UserIoInput> _stationInputDic;
        private Dictionary<string, UserIOOutPut> _stationOutputDic;
        private object obj_Param = null;
        private object obj_Point = null;
        private object obj_Config = null;
        private UIPage Page_Manual = null;
        ILog _log = LogManager.GetLogger("StationForm2");
        bool bStopMove = false;
        public StationForm(Stationbase stationBase,object obj_Param,object obj_Point,object obj_Config, UIPage ui_Manual=null)
        {
            InitializeComponent();
            _stationBase = stationBase;
            Name = stationBase.Name;
            this.obj_Point = obj_Point;
            this.obj_Param = obj_Param;
            this.obj_Config = obj_Config;
            Page_Manual = ui_Manual;

        }

        private void StationForm2_Resize(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView_PointInfo.Columns.Count; i++)
            {
                dataGridView_PointInfo.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }

         //   ResizePanAx();
        }

        private void btnShowVision_Click(object sender, EventArgs e)
        {
            //CameraForm.Instance.Show();
        }

        private void StationForm2_Load(object sender, EventArgs e)
        {
            IniPanAxis();
            UpdatadataGridView_PointInfo("");
            m_dicInput = IOMgr.GetInstace().GetInputDic();
            m_dicOutput = IOMgr.GetInstace().GetOutputDic();
            IEnumerable<KeyValuePair<string, IOMgr.IoDefine>> stationIoInDic = IOMgr.GetInstace().GetInputDic().Where(a => a.Value.PageName.Contains(_stationBase.Name)).Distinct();
            _stationBase.m_listIoInput = stationIoInDic.Select(a => a.Key.ToString()).ToList();
            IEnumerable<KeyValuePair<string, IOMgr.IoDefine>> stationIoOutDic = IOMgr.GetInstace().GetOutputDic().Where(a => a.Value.PageName.Contains(_stationBase.Name)).Distinct();
            _stationBase.m_listIoOutput = stationIoOutDic.Select(a => a.Key.ToString()).ToList();
            iniInput();
            iniOutput();
            UpDataAllIo();
            UpdataMotion();
            RegIOEvent();
            OpUpdataStationPoint.eventUpdatePointGridView += UpdatePosInGridView;
            if (Page_Manual != null)
            {
                tab_ManualTest.Controls.Add(Page_Manual);
                Page_Manual.Show();
            }
            if (obj_Config != null)
            {
                propertyGrid_Config.SelectedObject = obj_Config;
            }
            sys.g_eventRightChanged += ChangedUserRight;
            GlobalVariable.g_eventStationStateChanged += GlobalVariable_g_eventStationStateChanged;
            GlobalVariable_g_eventStationStateChanged(GlobalVariable.g_StationState);
            ParamSetMgr.GetInstance().m_eventLoadProductFile += UpdatadataGridView_PointInfo;//更新产品点位置信息
            ParamSetMgr.GetInstance().m_eventLoadProductFile += Updata_ParamSet;
            GlobalVariable.g_eventControlModeChanged += GlobalVariable_g_eventControlModeChanged;

            Language.LanguageHelp.GetInstance().Funtion_TransLate(this.Name);
        }
        private void GlobalVariable_g_eventControlModeChanged(ControlMode currRunMode)
        {
            GlobalVariable_g_eventStationStateChanged(GlobalVariable.g_StationState);
        }

        private void GlobalVariable_g_eventStationStateChanged(StationState currState)
        {
            if (InvokeRequired)
                this.BeginInvoke(new Action(() => GlobalVariable_g_eventStationStateChanged(currState)));
            else
            {
                if ((GlobalVariable.g_StationState == StationState.StationStateEmg || GlobalVariable.g_StationState == StationState.StationStateStop)
                   &&
                    GlobalVariable.g_ControlMode != ControlMode.Auto)
                {
                   if((int)sys.g_User._userRight >= (int)UserRight.Debug)
                    {
                        tabInput.Enabled = true;
                        tabOutput.Enabled = true;
                        panAxis.Enabled = true;
                        propertyGrid_Config.Enabled = true;
                        if (Page_Manual != null)
                            Page_Manual.Enabled = true;
                    }
                    PanParam.Enabled = true;
                }
                else
                {
                    tabInput.Enabled = false;
                    tabOutput.Enabled = false;
                    panAxis.Enabled = false;
                    if (Page_Manual != null)
                        Page_Manual.Enabled = false;
                    propertyGrid_Config.Enabled = false;
                    PanParam.Enabled = false;
                }

            }

        }

        public void  UpdatePosInGridView(string strStationName, string strPointName, int nColNum, double dCorVal,bool bSave)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new Action(() => { UpdatePosInGridView(strStationName, strPointName, nColNum, dCorVal, bSave); }));
            }
            else
            {
                if (_stationBase == null) return;
                if (_stationBase.Name != strStationName) return;
                if (dataGridView_PointInfo.Rows == null) return;
                if (dataGridView_PointInfo.Rows.Count == 0) return;
               

                for (int i = 0; i < dataGridView_PointInfo.Rows.Count; i++)
                {
                    if (dataGridView_PointInfo.Rows[i].Cells[0].Value != null &&
                        dataGridView_PointInfo.Rows[i].Cells[0].Value.ToString() == strPointName)
                    {
                       
                        dataGridView_PointInfo.Rows[i].Cells[nColNum].Value = dCorVal.ToString("F4");
                        if (!bSave) return;
                        Dictionary<string, PointInfo> staPoint = new Dictionary<string, PointInfo>();
                        //StationMgr.GetInstance().GetStation(this.Name).GetStationPointDic(ref staPoint);
                        if (!staPoint.ContainsKey(strPointName))
                            return;
                        PointInfo pointInfo = staPoint[strPointName];
                        switch (nColNum)
                        {
                            case 1:
                                if (pointInfo.pointX == dCorVal)
                                    return;
                                pointInfo.pointX = dCorVal;
                                break;
                            case 2:
                                if (pointInfo.pointY == dCorVal)
                                    return;
                                pointInfo.pointY = dCorVal;
                                break;
                            case 3:
                                if (pointInfo.pointZ == dCorVal)
                                    return;
                                pointInfo.pointZ = dCorVal;
                                break;
                            case 4:
                                if (pointInfo.pointU == dCorVal)
                                    return;
                                pointInfo.pointU = dCorVal;
                                break;
                            case 5:
                                if (pointInfo.pointTx == dCorVal)
                                    return;
                                pointInfo.pointTx = dCorVal;
                                break;
                            case 6:
                                if (pointInfo.pointTy == dCorVal)
                                    return;
                                pointInfo.pointTy = dCorVal;
                                break;

                        }
                        staPoint[strPointName] = pointInfo;
                        ConfigToolMgr.GetInstance().SaveStationPoint(this.Name, staPoint);

                        break;
                    }

                }
                Language.LanguageHelp.GetInstance().Funtion_TransLate(this.Name);

            }
        }
        /// <summary>
        /// 订阅IO状态
        /// </summary>
        private void RegIOEvent()
        {

            MotionMgr.GetInstace().m_eventChangeMotionIoOrPos += ChangeMotionIoStateAndPos;
            IOMgr.GetInstace().m_eventIoInputChanageByName += ChangedIoInState;
            IOMgr.GetInstace().m_eventIoOutputChanageByName += ChangedIoOutState;
        }
        public void CancekIoEvent()
        {
            MotionMgr.GetInstace().m_eventChangeMotionIoOrPos -= ChangeMotionIoStateAndPos;
            IOMgr.GetInstace().m_eventIoInputChanageByName -= ChangedIoInState;
            IOMgr.GetInstace().m_eventIoOutputChanageByName -= ChangedIoOutState;
        }

        public void UpDataAllIo()
        {
            Dictionary<string, IOMgr.IoDefine> dicInput = IOMgr.GetInstace().GetInputDic();
            foreach (var tem in dicInput)
            {
                if (_stationInputDic.ContainsKey(tem.Key))
                {
                    _stationInputDic[tem.Key].State = IOMgr.GetInstace().ReadIoInBit(tem.Key);
                }
            }

            Dictionary<string, IOMgr.IoDefine> dicOutput = IOMgr.GetInstace().GetOutputDic();

            foreach (var tem in dicOutput)
            {
                if (_stationOutputDic.ContainsKey(tem.Key))
                {
                    _stationOutputDic[tem.Key].State = IOMgr.GetInstace().ReadIoOutBit(tem.Key);
                }
            }


        }

        public void ChangedUserRight(User CurrentUser)
        {
            if (InvokeRequired)
                this.BeginInvoke(new Action(() => ChangedUserRight(CurrentUser)));
            else
            {
                switch ((int)CurrentUser._userRight)
                {
                    case (int)UserRight.Operator:
                        EnBtn(false);
                        EnPoints(false);
                        dataGridView_PointInfo.ReadOnly = true;
                        break;
                    case (int)UserRight.Debug:
                        dataGridView_PointInfo.ReadOnly = false;
                        EnBtn(true);
                        EnPoints(false);
                        break;
                    case (int)UserRight.Software:
                        EnPoints(true);
                        EnBtn(true);
                        dataGridView_PointInfo.ReadOnly = false;
                        break;
                    case (int)UserRight.Admin:
                        EnPoints(true);
                        EnBtn(true);
                        dataGridView_PointInfo.ReadOnly = false;
                        break;
                }
                UpdatadataGridView_ParamInfo(cbb_ParamType.Text, CurrentUser._userRight);
                GlobalVariable_g_eventStationStateChanged(GlobalVariable.g_StationState);
            }

        }
        /// <summary>
        /// 轴操作按钮
        /// </summary>
        /// <param name="bEnable"></param>
        void EnBtn(bool bEnable = true)
        {
            btnMoveN0.Enabled = bEnable;
            btnMoveP0.Enabled = bEnable;
            btnHome0.Enabled = bEnable;
            SWEnabled0.Enabled = bEnable;
            string btnMoveN = "btnMoveN";
            string btnMoveP = "btnMoveP";
            string btnHome = "btnHome";
            string SWEnabled = "SWEnabled";

            for (int i = 0; i < 6; i++)
            {
                var moveN = this.GetType().GetField(btnMoveN + i, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase)?.GetValue(this);
                (moveN as Control).Enabled = bEnable;
                var moveP = this.GetType().GetField(btnMoveP + i, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase)?.GetValue(this);
                (moveP as Control).Enabled = bEnable;
                var Home = this.GetType().GetField(btnHome + i, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase)?.GetValue(this);
                (Home as Control).Enabled = bEnable;
                var servoEnabled = this.GetType().GetField(SWEnabled + i, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase)?.GetValue(this);
                (servoEnabled as Control).Enabled = bEnable;
            }


            //button_stop.Enabled = bEnable;
            //userBtnPanel_Output.Enabled = bEnable;
        }
        /// <summary>
        /// 点位操作按钮
        /// </summary>
        /// <param name="bEnable"></param>
        void EnPoints(bool bEnable = true)
        {
            btnRecordPoint.Enabled = bEnable;
            btnSave.Enabled = bEnable;
            btnSingleAxisMove.Enabled = bEnable;
            dataGridView_PointInfo.ReadOnly = bEnable;

        }

        #region 轴操作

        /// <summary>
        /// 轴操作表头控件
        /// </summary>
        private List<Control> _titleControls;

        /// <summary>
        /// 轴操作控件
        /// </summary>
        private List<List<Control>> _axisControls;

        public bool BStopMove
        {
            get => bStopMove;
            set
            {
                bStopMove = value;
                // SetButtonsEnabled(bStopMove); 
            }
        }

        void SetButtonsEnabled(bool enabled)
        {
            //SWEnabled0.Enabled =enabled;
            foreach (var controls in _axisControls)
            {
                foreach (var item in controls)
                {
                    if (item is UISwitch)
                    {
                        item.Enabled = enabled;
                    }
                    if (item is UISymbolButton)
                    {
                        item.Enabled = enabled;
                    }
                    if (item is UITextBox)
                    {
                        item.Enabled = enabled;
                    }

                }
            }
            btnSave.Enabled = enabled;
            btnRecordPoint.Enabled = enabled;
            btnSingleAxisMove.Enabled = enabled;
        }
        /// <summary>
        /// 初始化轴的容器 
        /// </summary>
        void IniPanAxis()
        {
            _titleControls = new List<Control>();
            _titleControls.Add(lblAxName);
            _titleControls.Add(lblEnabled);
            _titleControls.Add(lblHome);
            _titleControls.Add(lblActPos);
            _titleControls.Add(lblCMDPos);
            _titleControls.Add(lblAlarm);
            _titleControls.Add(lblPM);
            _titleControls.Add(lblOrg);
            _titleControls.Add(lblNM);
            _titleControls.Add(lblEMG);
            _titleControls.Add(lbl_AlarmInfo);
            _titleControls.Add(cbMoveStyle);

            _axisControls = new List<List<Control>>();
            List<Control> tmpControls = new List<Control>
            {
                lblAxName0,
                SWEnabled0,
                btnHome0,
                txtActPos0,
                txtCMDPos0,
                lightAlarm0,
                lightPLim0,
                lightOrg0,
                lightNlim0,
                lightEmg0,
                lblErrInfo0,
                btnMoveN0,
                btnMoveP0
            };
            _axisControls.Add(tmpControls);

            {
                tmpControls = new List<Control>
                {
                    lblAxName1,
                    SWEnabled1,
                    btnHome1,
                    txtActPos1,
                    txtCMDPos1,
                    lightAlarm1,
                    lightPLim1,
                    lightOrg1,
                    lightNlim1,
                    lightEmg1,
                    lblErrInfo1,
                    btnMoveN1,
                    btnMoveP1
                };
                _axisControls.Add(tmpControls);
            }
            {
                tmpControls = new List<Control>
                {
                    lblAxName2,
                    SWEnabled2,
                    btnHome2,
                    txtActPos2,
                    txtCMDPos2,
                    lightAlarm2,
                    lightPLim2,
                    lightOrg2,
                    lightNlim2,
                    lightEmg2,
                    lblErrInfo2,
                    btnMoveN2,
                    btnMoveP2
                };
                _axisControls.Add(tmpControls);
            }
            {
                tmpControls = new List<Control>
                {
                    lblAxName3,
                    SWEnabled3,
                    btnHome3,
                    txtActPos3,
                    txtCMDPos3,
                    lightAlarm3,
                    lightPLim3,
                    lightOrg3,
                    lightNlim3,
                    lightEmg3,
                    lblErrInfo3,
                    btnMoveN3,
                    btnMoveP3
                };
                _axisControls.Add(tmpControls);
            }
            {
                tmpControls = new List<Control>
                {
                    lblAxName4,
                    SWEnabled4,
                    btnHome4,
                    txtActPos4,
                    txtCMDPos4,
                    lightAlarm4,
                    lightPLim4,
                    lightOrg4,
                    lightNlim4,
                    lightEmg4,
                    lblErrInfo4,
                   btnMoveN4,
                    btnMoveP4
                };
                _axisControls.Add(tmpControls);
            }
            {
                tmpControls = new List<Control>
                {
                    lblAxName5,
                    SWEnabled5,
                    btnHome5,
                    txtActPos5,
                    txtCMDPos5,
                    lightAlarm5,
                    lightPLim5,
                    lightOrg5,
                    lightNlim5,
                    lightEmg5,
                    lblErrInfo5,
                    btnMoveN5,
                    btnMoveP5
                };
                _axisControls.Add(tmpControls);
            }
            foreach (var controls in _axisControls)
            {
                foreach (var ctrl in controls)
                {
                    if (ctrl is UILight)
                    {
                        UILight light = ctrl as UILight;
                        light.StyleCustomMode = true;
                        light.OnColor = Color.Green;
                        light.OffColor = Color.Gray;

                    }
                    if (ctrl is UISwitch)
                    {
                        UISwitch light = ctrl as UISwitch;
                        light.StyleCustomMode = true;
                        light.ActiveColor = Color.Green;
                        light.InActiveColor = Color.Gray;

                    }

                }
            }

            int ctTop = lblAxName.Top + lblAxName.Height;
            ShowAxis(RowName.X, _stationBase.AxisX, ref ctTop);
            ShowAxis(RowName.Y, _stationBase.AxisY, ref ctTop);
            ShowAxis(RowName.Z, _stationBase.AxisZ, ref ctTop);
            ShowAxis(RowName.U, _stationBase.AxisU, ref ctTop);
            ShowAxis(RowName.Tx, _stationBase.AxisTx, ref ctTop);
            ShowAxis(RowName.Ty, _stationBase.AxisTy, ref ctTop);
            splitMain.SplitterDistance = ctTop + 50;
        }

        private void ShowAxis(RowName axName, int axNo, ref int ctTop)
        {
            if (axNo != -1)
            {
                foreach (var control in _axisControls[(int)axName])
                {
                    control.Top = ctTop + 10;
                    if (control.Name.Contains("lblAxName"))
                    {

                        control.Text = MotionMgr.GetInstace().GetAxisName(axNo);
                        dataGridView_PointInfo.Columns[(int)axName + 1].HeaderText = control.Text;
                    }
                }
                ctTop += 35;
            }
            else
            {
                foreach (var control in _axisControls[(int)axName])
                {
                    control.Visible = false;
                }

                dataGridView_PointInfo.Columns[(int)axName + 1].Visible = false;
            }


        }

        private void ResizePanAx()
        {
            var totalWidth = _titleControls.Sum(control => control.Width);
            var avgBlank = (panAxis.Width - totalWidth - lblAxName.Left) / (_titleControls.Count - 1);
            int nextLeft = lblAxName.Left;
            //调整表头
            foreach (var t in _titleControls)
            {
                t.Left = nextLeft;
                nextLeft += t.Width;
                nextLeft += avgBlank;
            }
            //对齐
            for (int i = 0; i < _titleControls.Count; i++)
            {
                for (int j = 0; j < _axisControls.Count; j++)
                {
                    _axisControls[j][i].Left = _titleControls[i].Left;
                }
            }

        }

        /// <summary>
        /// 上使能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SWEnabled0_Click(object sender, EventArgs e)
        {
            if (!(sender is UISwitch control)) return;
            var sw = control;

            var axNo = int.Parse(control.Name.Right(1));
            int absAxNo = GetAbsAxisNo(axNo);
            if (sw.Active)
            {
                MotionMgr.GetInstace().ServoOff((short)absAxNo);
            }
            else
            {
                MotionMgr.GetInstace().ServoOn((short)absAxNo);
            }
        }

        private int GetAbsAxisNo(int axNo)
        {
            int absAxNo = -1;//轴的绝对编号

            switch (axNo)
            {
                case 0:
                    absAxNo = _stationBase.AxisX;
                    break;
                case 1:
                    absAxNo = _stationBase.AxisY;
                    break;
                case 2:
                    absAxNo = _stationBase.AxisZ;
                    break;
                case 3:
                    absAxNo = _stationBase.AxisU;
                    break;
                case 4:
                    absAxNo = _stationBase.AxisTx;
                    break;
                case 5:
                    absAxNo = _stationBase.AxisTy;
                    break;
                default:
                    break;
            }

            return absAxNo;
        }

        private void SelMoveType(int nAxisNo, bool bPostive, int speed)
        {
            if (cbMoveStyle.SelectedItem == null || cbMoveStyle.SelectedItem.ToString() == "Jog")
                return;
            if (nAxisNo < 0)
                return;
            if (cbMoveStyle.SelectedItem == null || cbMoveStyle.Text == null || cbMoveStyle.Text == "")
                return;
            int k = bPostive ? 1 : -1;
            double distance = k * StringEx.ToDouble(cbMoveStyle.Text);
            string strError = "";
            if(!MotionMgr.GetInstace().RelativeMove(nAxisNo, distance, speed,ref strError))
            {
                this.ShowErrorDialog($"相对运动指令响应失败,错误信息={strError}");
            }
        }
        /// <summary>
        /// 负方向点动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMoveN_Click(object sender, EventArgs e)
        {
            UISymbolButton button = sender as UISymbolButton;
            BStopMove = false;

            var axNo = int.Parse(button.Name.Right(1));
            int absAxNo = GetAbsAxisNo(axNo);
            SelMoveType(absAxNo, false, 1);
        }

        /// <summary>
        /// 正方向点动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMoveP_Click(object sender, EventArgs e)
        {
            UISymbolButton button = sender as UISymbolButton;
            BStopMove = false;

            var axNo = int.Parse(button.Name.Right(1));
            int absAxNo = GetAbsAxisNo(axNo);
            SelMoveType(absAxNo, true, 1);
        }



        /// <summary>
        /// 负方向jog开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void JogStart(object sender, MouseEventArgs e)
        {
            if (!(sender is UISymbolButton control)) return;
            if (cbMoveStyle.SelectedItem != null && cbMoveStyle.SelectedItem.ToString() != "Jog")
                return;
            BStopMove = false;
            UISymbolButton button = sender as UISymbolButton;
            var axNo = int.Parse(button.Name.Right(1));
            int absAxNo = GetAbsAxisNo(axNo);

            bool bPositive;//方向
            if (control.Name.ToUpper().Contains("MOVEP"))
            {
                bPositive = true;
            }
            else if (control.Name.ToUpper().Contains("MOVEN"))
            {
                bPositive = false;
            }
            else
            {
                return;
            }
            if (MotionMgr.GetInstace().IsAxisNormalStop(absAxNo) != AxisState.Moving)
            {
                string strError = "";
                if (!MotionMgr.GetInstace().JogMove(absAxNo, bPositive, 0, 2,ref strError))
                {
                    this.ShowErrorDialog($"Jog运动指令响应失败,错误信息={strError}");
                }
            }
            ;
        }
        /// <summary>
        /// 负方向jog结束
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void JogEnd(object sender, MouseEventArgs e)
        {
            if (!(sender is UISymbolButton control)) return;
            if (cbMoveStyle.SelectedItem != null && cbMoveStyle.SelectedItem.ToString() != "Jog")
                return;
            UISymbolButton button = sender as UISymbolButton;
            var axNo = int.Parse(button.Name.Right(1));
            int absAxNo = GetAbsAxisNo(axNo);
            MotionMgr.GetInstace().StopAxis(absAxNo);
        }
        #endregion

        #region  点位

        public delegate void ModifyPoint(string StationName, string PointName);
        public static ModifyPoint EventModifyPoint;

        void UpdatadataGridView_PointInfo(string strFileName)
        {
            dataGridView_PointInfo.Rows.Clear();
            Dictionary<string, PointInfo> tempdic = _stationBase.GetFields<PointInfo>(obj_Point);
            if (tempdic == null)
                return;
            foreach (var temp in tempdic)
            {
                dataGridView_PointInfo.Rows.Add(temp.Key, temp.Value.pointX.ToString(),
                                                temp.Value.pointY.ToString(), temp.Value.pointZ.ToString(), temp.Value.pointU.ToString(),
                                                temp.Value.pointTx.ToString(), temp.Value.pointTy.ToString());

            }
        }
        void Updata_ParamSet(string strFileName)
        {
            UpdatadataGridView_ParamInfo("all", sys.g_User._userRight);
        }
        void UpdatadataGridView_PointInfo(string strFileName,string strType="")
        {
            dataGridView_PointInfo.Rows.Clear();
            Dictionary<string, PointInfo> tempdic = _stationBase.GetFields<PointInfo>(obj_Point);
            if (tempdic == null)
                return;

            foreach (var temp in tempdic)
            {
                if(temp.Value.str_Type==strType)
                {
                    dataGridView_PointInfo.Rows.Add(temp.Key, temp.Value.pointX.ToString(),
                        temp.Value.pointY.ToString(), temp.Value.pointZ.ToString(), temp.Value.pointU.ToString(),
                        temp.Value.pointTx.ToString(), temp.Value.pointTy.ToString());
                }
            }
        }

        void UpdatadataGridView_ParamInfo(string strType,UserRight userRight)
        {
            dataGridView_Param.Rows.Clear();
            Dictionary<string, ParamSet> dic_Param = _stationBase.GetFields<ParamSet>(obj_Param);
            if (dic_Param == null)
                return;
            cbb_ParamType.Items.Clear();
            dg_cbb_ParamType.Items.Clear();
            cbb_ParamType.Items.Add("all");
            foreach (var item in dic_Param)
            {
                if (!cbb_ParamType.Items.Contains(item.Value._ParamClass))
                    cbb_ParamType.Items.Add(item.Value._ParamClass);
                if (!dg_cbb_ParamType.Items.Contains(item.Value._ParamClass))
                    dg_cbb_ParamType.Items.Add(item.Value._ParamClass);
                if (item.Value._ParamRight <= userRight)
                {
                    if (item.Value._ParamClass == strType|| strType=="all")
                    {
                       int index = dataGridView_Param.Rows.Add(item.Key, item.Value._enuValType.ToString().Trim(),
                         item.Value._strParamVal, item.Value._strParamValMax, item.Value._strParamValMin,
                         item.Value._ParamRight.ToString(), item.Value._ParamClass.ToString(), item.Value.b_IsStartCheck);
                        if ((int)(UserRight)Enum.Parse(typeof(UserRight), dataGridView_Param.Rows[index].Cells[5].Value.ToString()) <= (int)sys.g_User._userRight)
                        {
                            //dataGridView_Param.Rows[index].ReadOnly = false;
                            dataGridView_Param.Rows[index].Cells[0].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[1].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[2].ReadOnly = false;
                            dataGridView_Param.Rows[index].Cells[3].ReadOnly = false;
                            dataGridView_Param.Rows[index].Cells[4].ReadOnly = false;
                            dataGridView_Param.Rows[index].Cells[5].ReadOnly = false;
                            dataGridView_Param.Rows[index].Cells[6].ReadOnly = false;
                            dataGridView_Param.Rows[index].Cells[7].ReadOnly = false;
                            dataGridView_Param.Rows[index].Visible = true;
                        }
                        else
                        {
                            dataGridView_Param.Rows[index].Cells[0].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[1].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[2].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[3].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[4].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[5].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[6].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[7].ReadOnly = true;
                            dataGridView_Param.Rows[index].Visible = true;
                        }

                    }
                }
            }
            cbb_ParamType.Text = strType;


        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string strPointNameErr = "";
            try
            {
                if (!this.ShowAskDialog("是否保存所有点位！", UIStyle.Blue)) return;
                Dictionary<string, PointInfo> staPoint_New = new Dictionary<string, PointInfo>();
                Dictionary<string, PointInfo> staPoint_Old = _stationBase.GetFields<PointInfo>(obj_Point);
                for (int i = 0; i < dataGridView_PointInfo.Rows.Count; i++)
                {
                    if (dataGridView_PointInfo.Rows[i].Cells[0].Value != null && dataGridView_PointInfo.Rows[i].Cells[0].Value.ToString() != "")
                    {
                        int index = 1;
                        PointInfo point = new PointInfo();
                        string strName = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name,  dataGridView_PointInfo.Rows[i].Cells[0].Value.ToString());
                        point.pointX = Convert.ToDouble(dataGridView_PointInfo.Rows[i].Cells[index++].Value);
                        point.pointY = Convert.ToDouble(dataGridView_PointInfo.Rows[i].Cells[index++].Value);
                        point.pointZ = Convert.ToDouble(dataGridView_PointInfo.Rows[i].Cells[index++].Value);
                        point.pointU = Convert.ToDouble(dataGridView_PointInfo.Rows[i].Cells[index++].Value);
                        point.pointTx = Convert.ToDouble(dataGridView_PointInfo.Rows[i].Cells[index++].Value);
                        point.pointTy = Convert.ToDouble(dataGridView_PointInfo.Rows[i].Cells[index++].Value);
                        point.userRight = staPoint_Old[strName].userRight;
                        point.str_Type = staPoint_Old[strName].str_Type;
                        string str_PointInfo = $"站位名称：{this.Name}，点位名称：{strName},X={point.pointX}，Y={point.pointY}，Z={point.pointZ}，U={point.pointU}，Tx={point.pointTx}，Ty={point.pointTy}";
                        staPoint_New.Add(strName, point);
                    }
                }
                if (obj_Point == null) return;
                FieldInfo[] list_Field = obj_Point.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                if (list_Field.Length <= 0) return;
                foreach (var item in list_Field)
                {
                    string str_Name = item.Name;
                    for (int i = 0; i < staPoint_New.Count; i++)
                    {
                        if (item.Name == staPoint_New.Keys.ToList()[i])
                        {
                            PointInfo pointOld = (PointInfo)item.GetValue(obj_Point);
                            PointInfo pointNew = staPoint_New.Values.ToList()[i];
                            if (pointOld.pointX!=pointNew.pointX|| pointOld.pointY != pointNew.pointY || pointOld.pointZ != pointNew.pointZ ||
                                pointOld.pointU != pointNew.pointU || pointOld.pointTx != pointNew.pointTx || pointOld.pointTy != pointNew.pointTy)
                            {
                                string strOldValue = "";
                                string strNewValue = "";
                                string strAxisName = "";
                                if(_stationBase.AxisX>-1)
                                {
                                    strAxisName = MotionMgr.GetInstace().GetAxisName(_stationBase.AxisX);
                                    strOldValue += $"{strAxisName}={pointOld.pointX},";
                                    strNewValue += $"{strAxisName}={pointNew.pointX},";
                                }
                                if (_stationBase.AxisY > -1)
                                {
                                    strAxisName = MotionMgr.GetInstace().GetAxisName(_stationBase.AxisY);
                                    strOldValue += $"{strAxisName}={pointOld.pointY},";
                                    strNewValue += $"{strAxisName}={pointNew.pointY},";
                                }
                                if (_stationBase.AxisZ > -1)
                                {
                                    strAxisName = MotionMgr.GetInstace().GetAxisName(_stationBase.AxisZ);
                                    strOldValue += $"{strAxisName}={pointOld.pointZ},";
                                    strNewValue += $"{strAxisName}={pointNew.pointZ},";
                                }
                                if (_stationBase.AxisU > -1)
                                {
                                    strAxisName = MotionMgr.GetInstace().GetAxisName(_stationBase.AxisU);
                                    strOldValue += $"{strAxisName}={pointOld.pointU},";
                                    strNewValue += $"{strAxisName}={pointNew.pointU},";
                                }
                                if (_stationBase.AxisTx > -1)
                                {
                                    strAxisName = MotionMgr.GetInstace().GetAxisName(_stationBase.AxisTx);
                                    strOldValue += $"{strAxisName}={pointOld.pointTx},";
                                    strNewValue += $"{strAxisName}={pointNew.pointTx},";
                                }
                                if (_stationBase.AxisTy > -1)
                                {
                                    strAxisName = MotionMgr.GetInstace().GetAxisName(_stationBase.AxisTy);
                                    strOldValue += $"{strAxisName}={pointOld.pointTy},";
                                    strNewValue += $"{strAxisName}={pointNew.pointTy},";
                                }
                                DeviceDataCollect.GetInstance().Function_PointChangeLog(_stationBase.Name, str_Name, strOldValue, strNewValue);
                            }

                            item.SetValue(obj_Point, staPoint_New.Values.ToList()[i]);
                        }
                    }
                }

                ConfigToolMgr.GetInstance().SaveStationPoint(this.Name, staPoint_New);
            }
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
                this.ShowErrorDialog($"点位数据：{strPointNameErr} 错误 ");
            }
        }

        private void btnRecordPoint_Click(object sender, EventArgs e)
        {
            string strPointErrName = "";
            try
            {
              
                //  if (!this.ShowAskDialog("是否记录此点到点位表格！", sys.UIStyle)) return;
                if( ! UIMessageDialog.ShowMessageDialog("是否记录此点到点位表格！", "Info", true, UIStyle.Blue, true))return ;
                int nAxisNot = _stationBase.AxisX;
                if (dataGridView_PointInfo.CurrentCell != null)
                {
                    int indexRow = dataGridView_PointInfo.CurrentCell.RowIndex;
                    int indexCol = dataGridView_PointInfo.CurrentCell.ColumnIndex;
                    string strPointName = dataGridView_PointInfo.Rows[indexRow].Cells[0].Value.ToString();
                    strPointErrName = strPointName;
                    string[] strPointNameArr = new string[dataGridView_PointInfo.Rows.Count];
                    for (int i = 0; i < dataGridView_PointInfo.Rows.Count; i++)
                    {
                        if (dataGridView_PointInfo.Rows[i].Cells[0].Value != null && dataGridView_PointInfo.Rows[i].Cells[0].Value.ToString() != "")
                            strPointNameArr[i] = dataGridView_PointInfo.Rows[i].Cells[0].Value.ToString();
                    }
                    PointInfo tempPoint = new PointInfo();
                    if (dataGridView_PointInfo.CurrentCell.ColumnIndex == 0)
                    {
                        int nAxisNo = StationMgr.GetInstance().GetStation(this.Name).AxisX;
                        tempPoint.pointX = (nAxisNo >= 0) ? MotionMgr.GetInstace().GetAxisActPos(nAxisNo) : 0;

                        nAxisNo = StationMgr.GetInstance().GetStation(this.Name).AxisY;
                        tempPoint.pointY = (nAxisNo >= 0) ? MotionMgr.GetInstace().GetAxisActPos(nAxisNo) : 0;

                        nAxisNo = StationMgr.GetInstance().GetStation(this.Name).AxisZ;
                        tempPoint.pointZ = (nAxisNo >= 0) ? MotionMgr.GetInstace().GetAxisActPos(nAxisNo) : 0;

                        nAxisNo = StationMgr.GetInstance().GetStation(this.Name).AxisU;
                        tempPoint.pointU = (nAxisNo >= 0) ? MotionMgr.GetInstace().GetAxisActPos(nAxisNo) : 0;

                        nAxisNo = StationMgr.GetInstance().GetStation(this.Name).AxisTx;
                        tempPoint.pointTx = (nAxisNo >= 0) ? MotionMgr.GetInstace().GetAxisActPos(nAxisNo) : 0;

                        nAxisNo = StationMgr.GetInstance().GetStation(this.Name).AxisTy;
                        tempPoint.pointTy = (nAxisNo >= 0) ? MotionMgr.GetInstace().GetAxisActPos(nAxisNo) : 0;

                    }
                    else
                    {
                        tempPoint.pointX = dataGridView_PointInfo.Rows[indexRow].Cells[1].Value == null ? 0 : StringEx.ToDouble(dataGridView_PointInfo.Rows[indexRow].Cells[1].Value.ToString());
                        tempPoint.pointY = dataGridView_PointInfo.Rows[indexRow].Cells[2].Value == null ? 0 : StringEx.ToDouble(dataGridView_PointInfo.Rows[indexRow].Cells[2].Value.ToString());
                        tempPoint.pointZ = dataGridView_PointInfo.Rows[indexRow].Cells[3].Value == null ? 0 : StringEx.ToDouble(dataGridView_PointInfo.Rows[indexRow].Cells[3].Value.ToString());
                        tempPoint.pointU = dataGridView_PointInfo.Rows[indexRow].Cells[4].Value == null ? 0 : StringEx.ToDouble(dataGridView_PointInfo.Rows[indexRow].Cells[4].Value.ToString());
                        tempPoint.pointTx = dataGridView_PointInfo.Rows[indexRow].Cells[5].Value == null ? 0 : StringEx.ToDouble(dataGridView_PointInfo.Rows[indexRow].Cells[5].Value.ToString());
                        tempPoint.pointTy = dataGridView_PointInfo.Rows[indexRow].Cells[6].Value == null ? 0 : StringEx.ToDouble(dataGridView_PointInfo.Rows[indexRow].Cells[6].Value.ToString());
                        int nAxisNo = -1;
                        switch (dataGridView_PointInfo.CurrentCell.ColumnIndex)
                        {
                            case 1:
                                nAxisNo = StationMgr.GetInstance().GetStation(this.Name).AxisX;
                                tempPoint.pointX = (nAxisNo >= 0) ? MotionMgr.GetInstace().GetAxisActPos(nAxisNo) : 0;
                                break;
                            case 2:
                                nAxisNo = StationMgr.GetInstance().GetStation(this.Name).AxisY;
                                tempPoint.pointY = (nAxisNo >= 0) ? MotionMgr.GetInstace().GetAxisActPos(nAxisNo) : 0;
                                break;
                            case 3:
                                nAxisNo = StationMgr.GetInstance().GetStation(this.Name).AxisZ;
                                tempPoint.pointZ = (nAxisNo >= 0) ? MotionMgr.GetInstace().GetAxisActPos(nAxisNo) : 0;
                                break;
                            case 4:
                                nAxisNo = StationMgr.GetInstance().GetStation(this.Name).AxisU;
                                tempPoint.pointU = (nAxisNo >= 0) ? MotionMgr.GetInstace().GetAxisActPos(nAxisNo) : 0;
                                break;
                            case 5:
                                nAxisNo = StationMgr.GetInstance().GetStation(this.Name).AxisTx;
                                tempPoint.pointTx = (nAxisNo >= 0) ? MotionMgr.GetInstace().GetAxisActPos(nAxisNo) : 0;
                                break;
                            case 6:
                                nAxisNo = StationMgr.GetInstance().GetStation(this.Name).AxisTy;
                                tempPoint.pointTy = (nAxisNo >= 0) ? MotionMgr.GetInstace().GetAxisActPos(nAxisNo) : 0;
                                break;
                        }
                    }
                    Dictionary<string, PointInfo> staPoint = new Dictionary<string, PointInfo>();
                    //StationMgr.GetInstance().GetStation(this.Name).GetStationPointDic(ref staPoint);
                    if(staPoint.ContainsKey(strPointName))
                    {
                        bool bChanged = tempPoint.pointX != staPoint[strPointName].pointX || tempPoint.pointY != staPoint[strPointName].pointY || tempPoint.pointZ != staPoint[strPointName].pointZ ||
                         tempPoint.pointTx != staPoint[strPointName].pointTx || tempPoint.pointTy != staPoint[strPointName].pointTy || tempPoint.pointU != staPoint[strPointName].pointU;

                        if (bChanged)
                            OpUpdataStationPoint.UpdatePointData(dataGridView_PointInfo, _stationBase.Name, strPointName, tempPoint,false);
                    }
                    else
                    {
                        OpUpdataStationPoint.UpdatePointData(dataGridView_PointInfo, _stationBase.Name, strPointName, tempPoint, false);
                    }
                    dataGridView_PointInfo.Rows[indexRow].Cells[1].Value = Math.Round(tempPoint.pointX, 3);
                    dataGridView_PointInfo.Rows[indexRow].Cells[2].Value = Math.Round(tempPoint.pointY, 3);
                    dataGridView_PointInfo.Rows[indexRow].Cells[3].Value = Math.Round(tempPoint.pointZ, 3);
                    dataGridView_PointInfo.Rows[indexRow].Cells[4].Value = Math.Round(tempPoint.pointU, 3);
                    dataGridView_PointInfo.Rows[indexRow].Cells[5].Value = Math.Round(tempPoint.pointTx, 3);
                    dataGridView_PointInfo.Rows[indexRow].Cells[6].Value = Math.Round(tempPoint.pointTy, 3);
                   // tempPoint.handedSystem = true;

                   
                   // StationMgr.GetInstance().GetStation(this.Name).AddPoint(strPointName, tempPoint);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
                this.ShowErrorDialog($"点位数据：{strPointErrName} 错误 ");
            }
        }

        private void btnSingleAxisMove_Click(object sender, EventArgs e)
        {

            if (!UIMessageDialog.ShowMessageDialog("是否进行单轴运动，请注意安全！", "Info", true, UIStyle.Blue, true)) return;
            if (dataGridView_PointInfo.CurrentCell == null)
                return;
            int indexRow = dataGridView_PointInfo.CurrentCell.RowIndex;
            int indexCol = dataGridView_PointInfo.CurrentCell.ColumnIndex;
            int nAxis = -1;

            switch (indexCol)
            {
                case 1:
                    nAxis = _stationBase.AxisX;
                    break;
                case 2:
                    nAxis = _stationBase.AxisY;
                    break;
                case 3:
                    nAxis = _stationBase.AxisZ;
                    break;
                case 4:
                    nAxis = _stationBase.AxisU;
                    break;
                case 5:
                    nAxis = _stationBase.AxisTx;
                    break;
                case 6:
                    nAxis = _stationBase.AxisTy;
                    break;
                default:
                    //tempInfoForm.m_OperateInfoText = "轴号选择错误";
                    // tempInfoForm.ShowDialog();
                    return;
            }
            double pos = Convert.ToDouble(dataGridView_PointInfo.CurrentCell.Value.ToString());
            if (nAxis != -1)
            {
                string strError = "";
                if (!MotionMgr.GetInstace().AbsMove(nAxis, pos, 2, ref strError))
                {
                    this.ShowErrorDialog($"绝对运动指令响应失败,错误信息={strError}");
                }
            }
        }

        #endregion

        #region  IO
        void iniInput()
        {
            Dictionary<string, IOMgr.IoDefine> dicInput = IOMgr.GetInstace().GetInputDic();//所有输出点字典
            List<string> pages = new List<string>(); //页名集合
            #region 获取每页最长名称

            Dictionary<string, string> pageMaxLengthDic = new Dictionary<string, string>();//每页最长字符<页名称，IO名称>
            foreach (var key in dicInput.Keys)
            {
                //不是本工站的继续循环
                if (!dicInput[key].PageName.Contains(_stationBase.Name)) continue;

                if (!pages.Contains(dicInput[key].PageName))
                {
                    pages.Add(dicInput[key].PageName);
                }
                if (!pageMaxLengthDic.ContainsKey(dicInput[key].PageName)) pageMaxLengthDic.Add(dicInput[key].PageName, key);
                if (pageMaxLengthDic[dicInput[key].PageName].Length < key.Length)
                {
                    pageMaxLengthDic[dicInput[key].PageName] = key;
                }
            }

            #endregion

            #region 获取页名查找页面的字典

            Dictionary<string, UIPage> pageDic = new Dictionary<string, UIPage>();
            tabInput.TabPages.Clear();
            if (pages.Count > 0)
            {
                foreach (var sPage in pages)
                {
                    UIPage uiPage = new UIPage { Text = sPage, AutoScroll = true };
                    tabInput.AddPage(uiPage);
                    pageDic.Add(sPage, uiPage);
                }
            }

            #endregion

            #region 将IO添加到对应的分页容器

            int panWidth = tabPage4.Width;
            _stationInputDic = new Dictionary<string, UserIoInput>();
            foreach (var uiPage in pageDic)
            {
                int top = 0;
                int left = 0;
                int maxLength = GetMaxInputLength(pageMaxLengthDic, uiPage);//获取最长IO长度作为列宽

                foreach (var item in dicInput)
                {
                    //不是本工站的继续循环
                    if (!item.Value.PageName.Contains(_stationBase.Name)) continue;
                    if (uiPage.Key == item.Value.PageName)
                    {
                        UserIoInput input = new UserIoInput();
                        pageDic[item.Value.PageName].Controls.Add(input);
                        _stationInputDic.Add(item.Key, input);
                        input.IOName = item.Key;
                        input.Height = 40;
                        input.OnColor = Color.Green;
                        input.OffColor = Color.Gray;
                        input.Left = left;
                        input.Top = top;
                        top += input.Height;
                    }
                }
            }

            #endregion

        }


        void iniOutput()
        {
            int outputNum = IOMgr.GetInstace().GetIoOutputNum();
            
            Dictionary<string, IOMgr.IoDefine> dicOutput = IOMgr.GetInstace().GetOutputDic();//所有输出点字典
            List<string> pages = new List<string>(); //页名集合
            #region 获取每页最长名称

            Dictionary<string, string> pageMaxLengthDic = new Dictionary<string, string>();//每页最长字符<页名称，IO名称>
            foreach (var key in dicOutput.Keys)
            {
                //不是本工站的继续循环
                if (!dicOutput[key].PageName.Contains(_stationBase.Name)) continue;
                if (!pages.Contains(dicOutput[key].PageName))
                {
                    pages.Add(dicOutput[key].PageName);
                }
                if (!pageMaxLengthDic.ContainsKey(dicOutput[key].PageName)) pageMaxLengthDic.Add(dicOutput[key].PageName, key);
                if (pageMaxLengthDic[dicOutput[key].PageName].Length < key.Length)
                {
                    pageMaxLengthDic[dicOutput[key].PageName] = key;
                }
            }

            #endregion

            #region 获取页名查找页面的字典

            Dictionary<string, UIPage> pageDic = new Dictionary<string, UIPage>();
            tabOutput.TabPages.Clear();
            if (pages.Count > 0)
            {
                foreach (var sPage in pages)
                {
                    UIPage uiPage = new UIPage();
                    uiPage.Text = sPage;
                    uiPage.AutoScroll = true;
                    tabOutput.AddPage(uiPage);
                    pageDic.Add(sPage, uiPage);
                }
            }

            #endregion



            #region 将IO添加到对应的分页容器

            int panWidth = tabPage4.Width;
            _stationOutputDic = new Dictionary<string, UserIOOutPut>();
            foreach (var uiPage in pageDic)
            {
                int top = 0;
                int left = 0;
                int maxLength = GetMaxOutputLength(pageMaxLengthDic, uiPage);//获取最长IO长度作为列宽

                foreach (var item in dicOutput)
                {
                    //不是本工站的继续循环
                    if (!item.Value.PageName.Contains(_stationBase.Name)) continue;
                    if (uiPage.Key == item.Value.PageName)
                    {
                        UserIOOutPut output = new UserIOOutPut();
                        pageDic[item.Value.PageName].Controls.Add(output);
                        output.StateChanged += Output_Click;
                        _stationOutputDic.Add(item.Key, output);
                        output.IOName = item.Key;
                        output.Height = 30;
                        output.OnColor = Color.Green;
                        output.OffColor = Color.Gray;
                        output.Left = left;
                        output.Top = top;
                        top += output.Height;
                    }
                }
            }

            #endregion

        }

        private void Output_Click(string ioName, bool state)
        {
            string strIOName = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name, ioName);
            bool bState = IOMgr.GetInstace().ReadIoOutBit(strIOName);
            IOMgr.GetInstace().WriteIoBit(ioName, !bState);
        }

        private int GetMaxOutputLength(Dictionary<string, string> pageMaxLengthDic, KeyValuePair<string, UIPage> uiPage)
        {
            string maxLengthIo = pageMaxLengthDic[uiPage.Key];
            UserIOOutPut tmpOutPut = new UserIOOutPut { IOName = maxLengthIo };
            return tmpOutPut.Width + 50;
        }

        private int GetMaxInputLength(Dictionary<string, string> pageMaxLengthDic, KeyValuePair<string, UIPage> uiPage)
        {
            string maxLengthIo = pageMaxLengthDic[uiPage.Key];
            UserIOOutPut tmpOutPut = new UserIOOutPut { IOName = maxLengthIo };
            return tmpOutPut.Width + 50;
        }

        #endregion

        private void UpdataMotion()
        {
            Stationbase psb = StationMgr.GetInstance().GetStation(this.Name);

            if (psb.AxisX >= 0)
            {
                AxisIOState axisIOState = new AxisIOState();
                AxisPos axisPos = new AxisPos();
                int axisNo = psb.AxisX;
                MotionMgr.GetInstace().GetAxisIOState(axisNo, ref axisIOState);
                MotionMgr.GetInstace().GetAxisPos(axisNo, ref axisPos);
                UpdataAxisIoAndPos(axisNo, axisIOState, axisPos);
            }
            if (psb.AxisY >= 0)
            {
                AxisIOState axisIOState = new AxisIOState();
                AxisPos axisPos = new AxisPos();
                int axisNo = psb.AxisY;
                MotionMgr.GetInstace().GetAxisIOState(axisNo, ref axisIOState);
                MotionMgr.GetInstace().GetAxisPos(axisNo, ref axisPos);
                UpdataAxisIoAndPos(axisNo, axisIOState, axisPos);
            }
            if (psb.AxisZ >= 0)
            {
                AxisIOState axisIOState = new AxisIOState();
                AxisPos axisPos = new AxisPos();
                int axisNo = psb.AxisZ;
                MotionMgr.GetInstace().GetAxisIOState(axisNo, ref axisIOState);
                MotionMgr.GetInstace().GetAxisPos(axisNo, ref axisPos);
                UpdataAxisIoAndPos(axisNo, axisIOState, axisPos);
            }
            if (psb.AxisU >= 0)
            {
                AxisIOState axisIOState = new AxisIOState();
                AxisPos axisPos = new AxisPos();
                int axisNo = psb.AxisU;
                MotionMgr.GetInstace().GetAxisIOState(axisNo, ref axisIOState);
                MotionMgr.GetInstace().GetAxisPos(axisNo, ref axisPos);
                UpdataAxisIoAndPos(axisNo, axisIOState, axisPos);
            }
            if (psb.AxisTx >= 0)
            {
                AxisIOState axisIOState = new AxisIOState();
                AxisPos axisPos = new AxisPos();
                int axisNo = psb.AxisTx;
                MotionMgr.GetInstace().GetAxisIOState(axisNo, ref axisIOState);
                MotionMgr.GetInstace().GetAxisPos(axisNo, ref axisPos);
                UpdataAxisIoAndPos(axisNo, axisIOState, axisPos);
            }
            if (psb.AxisTy >= 0)
            {
                AxisIOState axisIOState = new AxisIOState();
                AxisPos axisPos = new AxisPos();
                int axisNo = psb.AxisTy;
                MotionMgr.GetInstace().GetAxisIOState(axisNo, ref axisIOState);
                MotionMgr.GetInstace().GetAxisPos(axisNo, ref axisPos);
                UpdataAxisIoAndPos(axisNo, axisIOState, axisPos);
            }


        }

        void UpdataAxisIoAndPos(int nAxisNo, AxisIOState axisIOState, AxisPos pos)
        {
            if (nAxisNo == -1)
                return;
            Stationbase pbase = StationMgr.GetInstance().GetStation(this.Name);
            if (nAxisNo == pbase.AxisX)
            {
                SWEnabled0.Active = axisIOState._bSeverOn;
                lightAlarm0.State = axisIOState._bAlarm ? UILightState.On : UILightState.Off;
                lightPLim0.State = axisIOState._bLimtP ? UILightState.On : UILightState.Off;
                lightNlim0.State = axisIOState._bLimtN ? UILightState.On : UILightState.Off;
                lightOrg0.State = axisIOState._bOrg ? UILightState.On : UILightState.Off;
                lightEmg0.State = axisIOState._bEmg ? UILightState.On : UILightState.Off;
                txtActPos0.Text = pos._lActPos.ToString();
                txtCMDPos0.Text = pos._lCmdPos.ToString();
            }
            if (nAxisNo == pbase.AxisY)
            {
                SWEnabled1.Active = axisIOState._bSeverOn;
                lightAlarm1.State = axisIOState._bAlarm ? UILightState.On : UILightState.Off;
                lightPLim1.State = axisIOState._bLimtP ? UILightState.On : UILightState.Off;
                lightNlim1.State = axisIOState._bLimtN ? UILightState.On : UILightState.Off;
                lightOrg1.State = axisIOState._bOrg ? UILightState.On : UILightState.Off;
                lightEmg1.State = axisIOState._bEmg ? UILightState.On : UILightState.Off;
                txtActPos1.Text = pos._lActPos.ToString();
                txtCMDPos1.Text = pos._lCmdPos.ToString();

            }
            if (nAxisNo == pbase.AxisZ)
            {
                SWEnabled2.Active = axisIOState._bSeverOn;
                lightAlarm2.State = axisIOState._bAlarm ? UILightState.On : UILightState.Off;
                lightPLim2.State = axisIOState._bLimtP ? UILightState.On : UILightState.Off;
                lightNlim2.State = axisIOState._bLimtN ? UILightState.On : UILightState.Off;
                lightOrg2.State = axisIOState._bOrg ? UILightState.On : UILightState.Off;
                lightEmg2.State = axisIOState._bEmg ? UILightState.On : UILightState.Off;
                txtActPos2.Text = pos._lActPos.ToString();
                txtCMDPos2.Text = pos._lCmdPos.ToString();
            }
            if (nAxisNo == pbase.AxisU)
            {
                SWEnabled3.Active = axisIOState._bSeverOn;
                lightAlarm3.State = axisIOState._bAlarm ? UILightState.On : UILightState.Off;
                lightPLim3.State = axisIOState._bLimtP ? UILightState.On : UILightState.Off;
                lightNlim3.State = axisIOState._bLimtN ? UILightState.On : UILightState.Off;
                lightOrg3.State = axisIOState._bOrg ? UILightState.On : UILightState.Off;
                lightEmg3.State = axisIOState._bEmg ? UILightState.On : UILightState.Off;
                txtActPos3.Text = pos._lActPos.ToString();
                txtCMDPos3.Text = pos._lCmdPos.ToString();
            }
            if (nAxisNo == pbase.AxisTx)
            {
                SWEnabled4.Active = axisIOState._bSeverOn;
                lightAlarm4.State = axisIOState._bAlarm ? UILightState.On : UILightState.Off;
                lightPLim4.State = axisIOState._bLimtP ? UILightState.On : UILightState.Off;
                lightNlim4.State = axisIOState._bLimtN ? UILightState.On : UILightState.Off;
                lightOrg4.State = axisIOState._bOrg ? UILightState.On : UILightState.Off;
                lightEmg4.State = axisIOState._bEmg ? UILightState.On : UILightState.Off;
                txtActPos4.Text = pos._lActPos.ToString();
                txtCMDPos4.Text = pos._lCmdPos.ToString();
            }
            if (nAxisNo == pbase.AxisTy)
            {
                SWEnabled5.Active = axisIOState._bSeverOn;
                lightAlarm5.State = axisIOState._bAlarm ? UILightState.On : UILightState.Off;
                lightPLim5.State = axisIOState._bLimtP ? UILightState.On : UILightState.Off;
                lightNlim5.State = axisIOState._bLimtN ? UILightState.On : UILightState.Off;
                lightOrg5.State = axisIOState._bOrg ? UILightState.On : UILightState.Off;
                lightEmg5.State = axisIOState._bEmg ? UILightState.On : UILightState.Off;
                txtActPos5.Text = pos._lActPos.ToString();
                txtCMDPos5.Text = pos._lCmdPos.ToString();
            }
        }

        public void ChangedIoInState(string IoName, bool bStateCurrent)
        {
            if (InvokeRequired)
            {
                this.BeginInvoke(new Action(() => ChangedIoInState(IoName, bStateCurrent)));
            }
            else
            {
                if (_stationInputDic.ContainsKey(IoName))
                {
                    _stationInputDic[IoName].State = bStateCurrent;
                }

            }
        }
        public void ChangedIoOutState(string IoName, bool bStateCurrent)
        {
            if (InvokeRequired)
            {
                this.BeginInvoke(new Action(() => ChangedIoOutState(IoName, bStateCurrent)));
            }
            else
            {
                if (_stationOutputDic.ContainsKey(IoName))
                {
                    _stationOutputDic[IoName].State = bStateCurrent;
                }

            }
        }

        public void ChangeMotionIoStateAndPos(int index, bool[] bChangeBitGet, AxisIOState axisIOState, AxisPos axisPos,string strErrInfo)
        {
            bool[] bChangeBit = new bool[bChangeBitGet.Length];
            for (int i = 0; i < bChangeBit.Length; i++)
                bChangeBit[i] = bChangeBitGet[i];
            if (InvokeRequired)
            {
                this.BeginInvoke(new Action(() => ChangeMotionIoStateAndPos(index, bChangeBit, axisIOState, axisPos, strErrInfo)));
            }
            else
            {
                Stationbase pbase = StationMgr.GetInstance().GetStation(this.Name);
                if (index == pbase.AxisX)
                {
                    if (bChangeBit[0])
                        SWEnabled0.Active = axisIOState._bSeverOn;
                    if (bChangeBit[1])
                        ChangeState(lightAlarm0, axisIOState._bAlarm);
                    if (bChangeBit[2])
                        ChangeState(lightPLim0, axisIOState._bLimtP);
                    if (bChangeBit[3])
                        ChangeState(lightNlim0, axisIOState._bLimtN);
                    if (bChangeBit[4])
                        ChangeState(lightOrg0, axisIOState._bOrg);
                    if (bChangeBit[5])
                        ChangeState(lightEmg0, axisIOState._bEmg);
                    if (bChangeBit[6])
                        txtActPos0.Text = axisPos._lActPos.ToString();
                    if (bChangeBit[7])
                        txtCMDPos0.Text = axisPos._lCmdPos.ToString();
                    lblErrInfo0.Text = strErrInfo;
                }
                if (index == pbase.AxisY)
                {
                    if (bChangeBit[0])
                        SWEnabled1.Active = axisIOState._bSeverOn;
                    if (bChangeBit[1])
                        ChangeState(lightAlarm1, axisIOState._bAlarm);
                    if (bChangeBit[2])
                        ChangeState(lightPLim1, axisIOState._bLimtP);

                    if (bChangeBit[3])
                        ChangeState(lightNlim1, axisIOState._bLimtN);
                    if (bChangeBit[4])
                        ChangeState(lightOrg1, axisIOState._bOrg);
                    if (bChangeBit[5])
                        ChangeState(lightEmg1, axisIOState._bEmg);
                    if (bChangeBit[6])
                        txtActPos1.Text = axisPos._lActPos.ToString();
                    if (bChangeBit[7])
                        txtCMDPos1.Text = axisPos._lCmdPos.ToString();
                    lblErrInfo1.Text = strErrInfo;

                }
                if (index == pbase.AxisZ)
                {
                    if (bChangeBit[0])
                        SWEnabled2.Active = axisIOState._bSeverOn;
                    if (bChangeBit[1])
                        ChangeState(lightAlarm2, axisIOState._bAlarm);
                    if (bChangeBit[2])
                        ChangeState(lightPLim2, axisIOState._bLimtP);
                    if (bChangeBit[3])
                        ChangeState(lightNlim2, axisIOState._bLimtN);
                    if (bChangeBit[4])
                        ChangeState(lightOrg2, axisIOState._bOrg);
                    if (bChangeBit[5])
                        ChangeState(lightEmg2, axisIOState._bEmg);
                    if (bChangeBit[6])
                        txtActPos2.Text = axisPos._lActPos.ToString();
                    if (bChangeBit[7])
                        txtCMDPos2.Text = axisPos._lCmdPos.ToString();
                    lblErrInfo2.Text = strErrInfo;

                }
                if (index == pbase.AxisU)
                {
                    if (bChangeBit[0])
                        SWEnabled3.Active = axisIOState._bSeverOn;
                    if (bChangeBit[1])
                        ChangeState(lightAlarm3, axisIOState._bAlarm);
                    if (bChangeBit[2])
                        ChangeState(lightPLim3, axisIOState._bLimtP);
                    if (bChangeBit[3])
                        ChangeState(lightNlim3, axisIOState._bLimtN);
                    if (bChangeBit[4])
                        ChangeState(lightOrg3, axisIOState._bOrg);
                    if (bChangeBit[5])
                        ChangeState(lightEmg3, axisIOState._bEmg);
                    if (bChangeBit[6])
                        txtActPos3.Text = axisPos._lActPos.ToString();
                    if (bChangeBit[7])
                        txtCMDPos3.Text = axisPos._lCmdPos.ToString();
                    lblErrInfo3.Text = strErrInfo;

                }
                if (index == pbase.AxisTx)
                {
                    if (bChangeBit[0])
                        SWEnabled4.Active = axisIOState._bSeverOn;
                    if (bChangeBit[1])
                        ChangeState(lightAlarm4, axisIOState._bAlarm);
                    if (bChangeBit[2])
                        ChangeState(lightPLim4, axisIOState._bLimtP);
                    if (bChangeBit[3])
                        ChangeState(lightNlim4, axisIOState._bLimtN);
                    if (bChangeBit[4])
                        ChangeState(lightOrg4, axisIOState._bOrg);
                    if (bChangeBit[5])
                        ChangeState(lightEmg4, axisIOState._bEmg);
                    if (bChangeBit[6])
                        txtActPos4.Text = axisPos._lActPos.ToString();
                    if (bChangeBit[7])
                        txtCMDPos4.Text = axisPos._lCmdPos.ToString();
                    lblErrInfo4.Text = strErrInfo;

                }
                if (index == pbase.AxisTy)
                {
                    if (bChangeBit[0])
                        SWEnabled5.Active = axisIOState._bSeverOn;
                    if (bChangeBit[1])
                        ChangeState(lightAlarm5, axisIOState._bAlarm);
                    if (bChangeBit[2])
                        ChangeState(lightPLim5, axisIOState._bLimtP);
                    if (bChangeBit[3])
                        ChangeState(lightNlim5, axisIOState._bLimtN);
                    if (bChangeBit[4])
                        ChangeState(lightOrg5, axisIOState._bOrg);
                    if (bChangeBit[5])
                        ChangeState(lightEmg5, axisIOState._bEmg);
                    if (bChangeBit[6])
                        txtActPos5.Text = axisPos._lActPos.ToString();
                    if (bChangeBit[7])
                        txtCMDPos5.Text = axisPos._lCmdPos.ToString();
                    lblErrInfo5.Text = strErrInfo;

                }

            }

        }

        void ChangeState(UILight light, bool bval)
        {
            light.State = bval ? UILightState.On : UILightState.Off;
        }

        private void OnVisibleChanged(object sender, EventArgs e)
        {
            //if (Visible)
            //{
            //    //UpdataMotion();
            //    MotionMgr.GetInstace().m_eventChangeMotionIoOrPos += ChangeMotionIoStateAndPos;
            //    MotionMgr.GetInstace().m_eventChangeMotionConfig += ChangeMotionConfig;
            //    IOMgr.GetInstace().m_eventIoInputChanageByName += ChangedIoInState;
            //    IOMgr.GetInstace().m_eventIoOutputChanageByName += ChangedIoOutState;
            //    //ChagedPrItem("");


            //}
            //else
            //{
            //    MotionMgr.GetInstace().m_eventChangeMotionIoOrPos -= ChangeMotionIoStateAndPos;
            //    MotionMgr.GetInstace().m_eventChangeMotionConfig -= ChangeMotionConfig;
            //    IOMgr.GetInstace().m_eventIoInputChanageByName -= ChangedIoInState;
            //    IOMgr.GetInstace().m_eventIoOutputChanageByName -= ChangedIoOutState;
            //}
        }

        private void SWEnabled_ValueChanged(object sender, bool value)
        {
            if (!(sender is UISwitch control)) return;
            var axNo = int.Parse(control.Name.Right(1));
            var sw = control;
            if (sw.Active)
            {
                MotionMgr.GetInstace().ServoOff((short)axNo);
            }
            else
            {
                MotionMgr.GetInstace().ServoOn((short)axNo);
            }
        }

        private void btnHome0_Click(object sender, EventArgs e)
        {
            UISymbolButton button = sender as UISymbolButton;

            BStopMove = false;
            var axNo = int.Parse(button.Name.Right(1));
            int absAxNo = GetAbsAxisNo(axNo);
            HomeAction(absAxNo, button);
        }
        public void HomeAction(int nAxisNo, UISymbolButton button)
        {
            BStopMove = false;
            button.Style = UIStyle.Orange;

            bool bHomeOK = false;
            string str_Error = "";
            try
            {
                Task ts = new Task(delegate ()
                {
                    // if (axiscofig.motorType == MotorType.SEVER)
                    //     MotionMgr.GetInstace().ServoOn((short)nAxisNo);
                    bHomeOK = MotionMgr.GetInstace().Home(nAxisNo, 0,ref str_Error);
                });
                ts.Start();
                ts.ContinueWith((ts1) =>
                {
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Restart();
                    while (!MotionMgr.GetInstace().IsHomeNormalStop(nAxisNo))
                    {
                        if (stopwatch.ElapsedMilliseconds > 120 * 1000 || BStopMove)
                        {
                            MotionMgr.GetInstace().StopAxis(nAxisNo);
                            this.ShowErrorDialog($"{MotionMgr.GetInstace().GetAxisName(nAxisNo)}90秒超时 回原点失败,错误信息={str_Error}");
                            AxisState axisState = MotionMgr.GetInstace().IsAxisNormalStop(nAxisNo);
                            MotionMgr.GetInstace().IsHomeNormalStop(nAxisNo);
                            MotionMgr.GetInstace().ReasetAxisHomeFinishFlag(nAxisNo);
                            goto Exception_ENDX;
                        }
                    }
                    Thread.Sleep(800);
                    if (bHomeOK)
                    {
                        MotionMgr.GetInstace().SetAxisActualPos(nAxisNo, 0);
                        MotionMgr.GetInstace().SetAxisCmdPos(nAxisNo, 0);
                        MotionMgr.GetInstace().SetAxisHomeFinishFlag(nAxisNo);
                    }
                Exception_ENDX:
                    button.Invoke(
                          new Action(() =>
                          {
                              button.Style = UIStyle.Blue;
                          })
                     );
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            BStopMove = true;
            int nAxisNo = _stationBase.AxisX;
            if (nAxisNo >= 0)
                MotionMgr.GetInstace().StopAxis(nAxisNo);
            nAxisNo = _stationBase.AxisY;
            if (nAxisNo >= 0)
                MotionMgr.GetInstace().StopAxis(nAxisNo);
            nAxisNo = _stationBase.AxisZ;
            if (nAxisNo >= 0)
                MotionMgr.GetInstace().StopAxis(nAxisNo);
            nAxisNo = _stationBase.AxisU;
            if (nAxisNo >= 0)
                MotionMgr.GetInstace().StopAxis(nAxisNo);
            nAxisNo = _stationBase.AxisTx;
            if (nAxisNo >= 0)
                MotionMgr.GetInstace().StopAxis(nAxisNo);
            nAxisNo = _stationBase.AxisTy;
            if (nAxisNo >= 0)
                MotionMgr.GetInstace().StopAxis(nAxisNo);
            btnHome0.Style = UIStyle.Blue;
            btnHome1.Style = UIStyle.Blue;
            btnHome2.Style = UIStyle.Blue;
            btnHome3.Style = UIStyle.Blue;
            btnHome4.Style = UIStyle.Blue;
            btnHome5.Style = UIStyle.Blue;
        }

        private void SWEnabled0_ValueChanged(object sender, bool value)
        {

        }


        private void uiTitlePanel1_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                RegIOEvent();
            }
            else
            {
                CancekIoEvent();
            }
        }

        private void cbb_PointType_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdatadataGridView_PointInfo("","");
        }

        private void dataGridView_Param_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void cbb_ParamType_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdatadataGridView_ParamInfo(cbb_ParamType.Text,sys.g_User._userRight);
        }
        List<string> ItemName = new List<string>();
        private bool Check()
        {
            try
            {
                ItemName.Clear();
                for (int i = 0; i < dataGridView_Param.Rows.Count; i++)
                {
                    string name = dataGridView_Param.Rows[i].Cells[0].Value.ToString().Trim();
                    string sort = dataGridView_Param.Rows[i].Cells[6].Value.ToString().Trim();
                    string type = dataGridView_Param.Rows[i].Cells[1].Value.ToString().Trim();
                    string value = dataGridView_Param.Rows[i].Cells[2].Value.ToString().Trim();
                    string Max = dataGridView_Param.Rows[i].Cells[3].Value.ToString().Trim();
                    string Min = dataGridView_Param.Rows[i].Cells[4].Value.ToString().Trim();
                    dynamic v; dynamic vMax; dynamic vMin;

                    if (type == "boolUnit")
                    {
                        if (value.ToLower() != "true" && value.ToLower() != "false")
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，请输入false或者true");
                            return false;
                        }
                        if (Max.ToLower() != "true" && Max.ToLower() != "false")
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，Max设置失败，请输入false或者true");
                            return false;
                        }
                        if (Min.ToLower() != "true" && Min.ToLower() != "false")
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，min设置失败，请输入false或者true");
                            return false;
                        }
                    }
                    else if (type == "intUnit")
                    {

                        if (value.Contains("."))
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，有小数点");
                            return false;
                        }
                        if (Max.Contains("."))
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，Max设置失败，有小数点");
                            return false;
                        }
                        if (Min.Contains("."))
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，min设置失败，有小数点");
                            return false;
                        }
                        try
                        {
                            v = Convert.ToInt32(value);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，请输入int类型数据");
                            return false;
                        }
                        try
                        {
                            vMax = Convert.ToInt32(Max);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，Max设置失败，请输入int类型数据");
                            return false;
                        }
                        try
                        {
                            vMin = Convert.ToInt32(Min);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，min设置失败，请输入int类型数据");
                            return false;
                        }
                        if (v > vMax || v < vMin)
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，不在规格内");
                            return false;
                        }
                    }
                    else if (type == "doubleUnit")
                    {
                        try
                        {
                            v = Convert.ToDouble(value);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，请输入int类型数据");
                            return false;
                        }
                        try
                        {
                            vMax = Convert.ToDouble(Max);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，Max设置失败，请输入int类型数据");
                            return false;
                        }
                        try
                        {
                            vMin = Convert.ToDouble(Min);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，min设置失败，请输入int类型数据");
                            return false;
                        }
                        if (v > vMax || v < vMin)
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，不在规格内");
                            return false;
                        }

                    }
                    else if (type == "stringUnit")
                    {

                    }
                    if (ItemName.Contains(name))
                    {
                        UIMessageBox.ShowError($"第{i}行存在重名参数{name},请检查");
                        return false;
                    }
                    ItemName.Add(name);
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
                return false;
            }

        }

        private void btn_SaveParam_Click(object sender, EventArgs e)
        {
            try
            {
                if (!this.ShowAskDialog("是否保存该工站参数！", UIStyle.Blue)) return;
                if (!Check())
                    return;
                Dictionary<string, ParamSet> dic_Param = _stationBase.GetFields<ParamSet>(obj_Param);
                if (dic_Param == null)
                    return;
                Dictionary<string, ParamSet> staParam_New = dic_Param;
                for (int i = 0; i < dataGridView_Param.Rows.Count; i++)
                {
                    if (dataGridView_Param.Rows[i].Cells[0].Value != null && dataGridView_Param.Rows[i].Cells[0].Value.ToString() != "")
                    {
                         int nIndexOfMax = 3;
                         int nIndexOfMin = 4;
                         int nIndexOfVal = 2;
                         int nIndexOfClass = 6;
                         int nIndexOfRight = 5;
                         int nIndexOfName = 0;
                         int nIndexOfUnit = 1;
                         int nIndexOfbIsStartCheck = 7;
                        string strParamName = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name,  dataGridView_Param.Rows[i].Cells[nIndexOfName].Value.ToString());
                        string strValType = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name,  dataGridView_Param.Rows[i].Cells[nIndexOfUnit].Value.ToString());
                        string strParamVal = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name,  dataGridView_Param.Rows[i].Cells[nIndexOfVal].Value.ToString());
                        string strParamValMax = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name,  dataGridView_Param.Rows[i].Cells[nIndexOfMax].Value.ToString());
                        string strParamValMin = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name,  dataGridView_Param.Rows[i].Cells[nIndexOfMin].Value.ToString());
                        string strParamRight = dataGridView_Param.Rows[i].Cells[nIndexOfRight].Value.ToString();// "Operator";
                        string strParamClass = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name,  dataGridView_Param.Rows[i].Cells[nIndexOfClass].Value.ToString());
                        ParamSet paramSet = new ParamSet()
                        {
                            _strParamUnit = strParamName,
                            _enuValType = dataGridView_Param.Rows[i].Cells[nIndexOfUnit].Value == null ? ParamSetUnit.doubleUnit : (ParamSetUnit)Enum.Parse(typeof(ParamSetUnit), strValType),
                            _strParamVal = dataGridView_Param.Rows[i].Cells[nIndexOfVal].Value == null ? "0" : strParamVal,
                            _strParamValMax = dataGridView_Param.Rows[i].Cells[nIndexOfMax].Value == null ? "0" : strParamValMax,
                            _strParamValMin = dataGridView_Param.Rows[i].Cells[nIndexOfMin].Value == null ? "0" : strParamValMin,
                            _ParamRight = dataGridView_Param.Rows[i].Cells[nIndexOfRight].Value == null ? UserRight.Operator : (UserRight)Enum.Parse(typeof(UserRight), strParamRight),
                            _ParamClass = dataGridView_Param.Rows[i].Cells[nIndexOfClass].Value == null ? "综合" : strParamClass,
                            b_IsStartCheck = Convert.ToBoolean(dataGridView_Param.Rows[i].Cells[nIndexOfbIsStartCheck].Value)
                        };
                        if (paramSet._enuValType==ParamSetUnit.boolUnit)
                        {
                            paramSet._strParamVal = Convert.ToBoolean(paramSet._strParamVal);
                            paramSet._strParamValMax = Convert.ToBoolean(paramSet._strParamValMax);
                            paramSet._strParamValMin = Convert.ToBoolean(paramSet._strParamValMin);
                        }
                        else if (paramSet._enuValType == ParamSetUnit.doubleUnit)
                        {
                            paramSet._strParamVal = Convert.ToDouble(paramSet._strParamVal);
                            paramSet._strParamValMax = Convert.ToDouble(paramSet._strParamValMax);
                            paramSet._strParamValMin = Convert.ToDouble(paramSet._strParamValMin);
                        }
                        else if (paramSet._enuValType == ParamSetUnit.intUnit)
                        {
                            paramSet._strParamVal = Convert.ToInt32(paramSet._strParamVal);
                            paramSet._strParamValMax = Convert.ToInt32(paramSet._strParamValMax);
                            paramSet._strParamValMin = Convert.ToInt32(paramSet._strParamValMin);
                        }
                        else if (paramSet._enuValType == ParamSetUnit.stringUnit)
                        {
                            paramSet._strParamVal = Convert.ToString(paramSet._strParamVal);
                            paramSet._strParamValMax = Convert.ToString(paramSet._strParamValMax);
                            paramSet._strParamValMin = Convert.ToString(paramSet._strParamValMin);
                        }
                        string str_PointInfo = $"站位名称：{this.Name}，参数名称：{strParamName}，参数值：{strParamVal}";
                        staParam_New[strParamName] = paramSet;
                    }
                }
                if (obj_Param == null) return;
                FieldInfo[] list_Field = obj_Param.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                if (list_Field.Length <= 0) return;
                foreach (var item in list_Field)
                {
                    string str_Name = item.Name;
                    for (int i = 0; i < staParam_New.Count; i++)
                    {
                        if (item.Name == staParam_New.Keys.ToList()[i])
                        {
                            ParamSet paramOld = (ParamSet)item.GetValue(obj_Param);
                            ParamSet paramNew = staParam_New.Values.ToList()[i];
                            if (paramOld._strParamVal != paramNew._strParamVal)
                                BaseDll.DeviceDataCollect.GetInstance().Function_ParamChangeLog(this.Name, str_Name, Convert.ToString(paramOld._strParamVal), Convert.ToString(paramNew._strParamVal), "值");
                            if (paramOld._strParamValMax != paramNew._strParamValMax)
                                BaseDll.DeviceDataCollect.GetInstance().Function_ParamChangeLog(this.Name, str_Name, Convert.ToString(paramOld._strParamValMax), Convert.ToString(paramNew._strParamValMax), "最大值");
                            if (paramOld._strParamValMin != paramNew._strParamValMin)
                                BaseDll.DeviceDataCollect.GetInstance().Function_ParamChangeLog(this.Name, str_Name, Convert.ToString(paramOld._strParamValMin), Convert.ToString(paramNew._strParamValMin), "最小值");

                            item.SetValue(obj_Param, staParam_New.Values.ToList()[i]);
                        }
                    }
                }

                ConfigToolMgr.GetInstance().SaveStationParam(this.Name, staParam_New);
                for (int i = 0; i < dataGridView_Param.RowCount; i++)
                {

                    if (dataGridView_Param.Rows[i].Cells[2].Style.BackColor == Color.Yellow)
                        dataGridView_Param.Rows[i].Cells[2].Style.BackColor = Color.White;
                    if (dataGridView_Param.Rows[i].Cells[3].Style.BackColor == Color.Yellow)
                        dataGridView_Param.Rows[i].Cells[3].Style.BackColor = Color.White;
                    if (dataGridView_Param.Rows[i].Cells[4].Style.BackColor == Color.Yellow)
                        dataGridView_Param.Rows[i].Cells[4].Style.BackColor = Color.White;
                }

                Language.LanguageHelp.GetInstance().Funtion_TransLate(this.Name);
            }
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
            }
        }

        private void dataGridView_Param_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                int RowIndex = dataGridView_Param.CurrentCell.RowIndex;
                if ((int)(UserRight)Enum.Parse(typeof(UserRight), dataGridView_Param.Rows[RowIndex].Cells[5].Value.ToString()) > (int)sys.g_User._userRight)
                    return;
                int ColumnIndex = dataGridView_Param.CurrentCell.ColumnIndex;
                if (ColumnIndex == 2 || ColumnIndex == 3 || ColumnIndex == 4)
                {
                    string valType = ColumnIndex == 2 ? "参数值" : ColumnIndex == 3 ? " 最大值" : "最小值";
                    string oldData = dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString();
                    string paramname = dataGridView_Param[0, RowIndex].Value.ToString();
                    if (ColumnIndex == 2 && (dataGridView_Param[1, RowIndex].Value != null &&
                         dataGridView_Param[3, RowIndex].Value != null &&
                         dataGridView_Param[4, RowIndex].Value != null
                         ))
                    {

                        InputDataToDataGridView(RowIndex, ColumnIndex, dataGridView_Param[3, RowIndex].Value.ToString(), dataGridView_Param[4, RowIndex].Value.ToString());
                        btnSave.Focus();
                        string newData = dataGridView_Param[ColumnIndex, RowIndex].Value.ToString();
                        UIMessageTipHelper.ShowInfoTip(dataGridView_Param.GetParentForm(), $"参数：{paramname}  {valType}被修改 原值：{oldData} --> 现值:{newData}", TipStyle.Gray, 1500);
                    }
                    if (dataGridView_Param[1, RowIndex].Value != null && (ColumnIndex == 3 || ColumnIndex == 4))
                    {
                        InputDataToDataGridView(RowIndex, ColumnIndex, "", "");
                        btnSave.Focus();
                        string newData = dataGridView_Param[ColumnIndex, RowIndex].Value.ToString();
                        UIMessageTipHelper.ShowInfoTip(dataGridView_Param.GetParentForm(), $"参数：{paramname} {valType}被修改 原值：{oldData} --> 现值:{newData}", TipStyle.Gray, 1500);

                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
            }
        }

        private void InputDataToDataGridView(int RowIndex, int ColumnIndex, string max, string min)
        {
            bool bRtnInput = false;
            switch (Enum.Parse(typeof(ParamSetUnit), dataGridView_Param[1, RowIndex].Value?.ToString()))
            {

                case ParamSetUnit.intUnit:
                    int nMax = max != "" ? max.ToInt() : int.MaxValue;
                    int nMin = min != "" ? min.ToInt() : int.MinValue;

                    int valueInt = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? 0 : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString().ToInt();
                    bRtnInput = UIInputDialog.InputIntegerDialog(this, ref valueInt, true, "请输入数字：");
                    if (bRtnInput)
                    {

                        if (dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString().ToInt() != valueInt)
                        {
                            ChangeDataGridViewCellBackColor(dataGridView_Param, RowIndex, ColumnIndex);
                            dataGridView_Param[ColumnIndex, RowIndex].Value = valueInt;
                        }
                    }
                    int dOldValint = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? 0 : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString().ToInt();
                    if (valueInt == dOldValint) bRtnInput = true;
                    break;
                case ParamSetUnit.doubleUnit:
                    double dMax = max != "" ? max.ToDouble() : double.MaxValue;
                    double dMin = min != "" ? min.ToDouble() : double.MinValue;
                    double valueDouble = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? 0 : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString().ToDouble();
                    bRtnInput = UIInputDialog.InputDoubleDialog(this, ref valueDouble, 3, true, "请输入数字：");
                    if (bRtnInput)
                    {
                        if (dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString().ToDouble() != valueDouble)
                        {

                            ChangeDataGridViewCellBackColor(dataGridView_Param, RowIndex, ColumnIndex);
                            dataGridView_Param[ColumnIndex, RowIndex].Value = valueDouble;
                        }
                    }
                    double dOldValdouble = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? 0 : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString().ToDouble();
                    if (valueDouble == dOldValdouble)
                        bRtnInput = true;
                    break;
                case ParamSetUnit.boolUnit:
                    int selectIndex = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? 0 : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString().ToUpper() == "TRUE" ? 0 : 1;
                    List<string> items = new List<string>() { "True", "False" };
                    bRtnInput = this.ShowSelectDialog(ref selectIndex, items, "是否选择".Trim(), "", UIStyle.Blue);
                    if (bRtnInput)
                    {
                        if (dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString() != items[selectIndex])
                        {
                            ChangeDataGridViewCellBackColor(dataGridView_Param, RowIndex, ColumnIndex);
                            dataGridView_Param[ColumnIndex, RowIndex].Value = items[selectIndex];
                        }
                    }
                    if (dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString() == items[selectIndex])
                        bRtnInput = true;


                    break;
                case ParamSetUnit.stringUnit:
                    string valueString = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? "" : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString();
                    bRtnInput = UIInputDialog.InputStringDialog(this, ref valueString, false, "请输入字符：");
                    if (bRtnInput)
                    {
                        if (dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString() != valueString)
                        {
                            dataGridView_Param[ColumnIndex, RowIndex].Value = valueString;
                            ChangeDataGridViewCellBackColor(dataGridView_Param, RowIndex, ColumnIndex);
                        }
                    }
                    if (valueString == dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString())
                        bRtnInput = true;

                    break;

            }
            if (!bRtnInput)
                this.ShowMessageDialog("输入值错误，可能超出上下限，请检查", "Err", true, UIStyle.Blue);
        }
        public void ChangeDataGridViewCellBackColor(DataGridView dataGridView, int RowIndex, int ColumnIndex)
        {
            DataGridViewRow dr = (dataGridView as DataGridView).Rows[RowIndex];
            dr.Cells[ColumnIndex].Style.BackColor = Color.Yellow;
            dataGridView_Param.Invalidate(dr.Cells[ColumnIndex].ContentBounds);
            dr.Cells[ColumnIndex].Selected = false;
        }

        private void dataGridView_Param_Click(object sender, EventArgs e)
        {
            try
            {
                int RowIndex = dataGridView_Param.CurrentCell.RowIndex;
                int ColumnIndex = dataGridView_Param.CurrentCell.ColumnIndex;
                if (ColumnIndex >= 0 && RowIndex >= 0)
                {
                    richTxt_参数说明.Text = $"参数名:{ dataGridView_Param[0, RowIndex].Value}" + Environment.NewLine;
                    richTxt_参数说明.Text += $"当前值:{ dataGridView_Param[2, RowIndex].Value}" + Environment.NewLine;
                    richTxt_参数说明.Text += $"允许最大值:{ dataGridView_Param[3, RowIndex].Value}" + Environment.NewLine;
                    richTxt_参数说明.Text += $"允许最小值:{ dataGridView_Param[4, RowIndex].Value}" + Environment.NewLine;
                    if (dataGridView_Param[0, RowIndex].Value == null)
                        return;
                    var de = ParamSetMgr.GetInstance().paramValue?.Find(p => p.ParamName == (dataGridView_Param[0, RowIndex].Value).ToString().Trim());
                    if (de == null)
                    {
                        richTxt_参数说明.Text += $"参数描述:还未添加描述，请在Description.xml中添加" + Environment.NewLine;
                    }
                    else
                    {
                        richTxt_参数说明.Text += $"参数描述:{ de.Description}" + Environment.NewLine;
                    }


                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
                return;
            }
        }

        private void btn_ConfigSave_Click(object sender, EventArgs e)
        {
            try
            {
                CommonTools.ConfigToolMgr.GetInstance().SaveStationConfig(this.Name, propertyGrid_Config.SelectedObject);
            }
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
                return;
            }
        }

        private void uiLabel6_Click(object sender, EventArgs e)
        {

        }
    }

    public class UpdataStationPointData
    {
        [XmlElement("源工站名")]
        /// <summary>
        /// 源工位名
        /// </summary>
        public string srcStationName;
        [XmlElement("源点位名")]
        /// <summary>
        /// 源点点位名
        /// </summary>
        public string srcPointName;
        [XmlElement("源轴名")]
        /// <summary>
        /// 源轴名
        /// </summary>
        public string srcAxisName;

        [XmlElement("目标工站名")]
        /// <summary>
        /// 目标工站名
        /// </summary>
        public string dstStationName;
        [XmlElement("目标点位名")]
        /// <summary>
        /// 目标点位名
        /// </summary>
        public string dstPointName;
        ///// <summary>
        ///// 目标轴名
        ///// </summary>
        //public string dstAxisName;
    }

    public class OpUpdataStationPoint
    {
        private static List<UpdataStationPointData> _UpdataStationPointDatas = new List<UpdataStationPointData>();


        public static void AddUpdataStationPointData(UpdataStationPointData item)
        {
            _UpdataStationPointDatas.Add(item);
        }

        public static void AddUpdataStationPointData(string strSrcSationName, string strSrcPointName, string strSrcAxisName,
            string strDstSationName, string strDstPointName/*, string strDstAxisName*/)
        {
            UpdataStationPointData item = new UpdataStationPointData()
            {
                srcStationName = strSrcSationName,
                srcPointName = strSrcPointName,
                srcAxisName = strSrcAxisName,
                dstStationName = strDstSationName,
                dstPointName = strDstPointName,
                //dstAxisName= strDstAxisName,
            };

            _UpdataStationPointDatas.Add(item);
        }
        public static void Clear()
        {
            _UpdataStationPointDatas.Clear();
        }

        public static void Read(string path = "")
        {
            path = path == "" ? path = "..\\_Updata\\点位坐标关联配置.xml" : path;
            if (File.Exists(path))
            {
                List<UpdataStationPointData> obj = (List<UpdataStationPointData>)AccessXmlSerializer.XmlToObject(path, typeof(List<UpdataStationPointData>));
                if (obj != null)
                {
                    _UpdataStationPointDatas = obj;
                    if (_UpdataStationPointDatas.Count == 0)
                    {
                        AddUpdataStationPointData("源工站名事例", "源点位名事例", "源轴名事例", "目标工站名事例", "目标点位名事例");
                        Save(path);
                    }
                }
                else
                {
                    AddUpdataStationPointData("源工站名事例", "源点位名事例", "源轴名事例", "目标工站名事例", "目标点位名事例");
                    Save(path);
                }
            }
            else
            {
                AddUpdataStationPointData("源工站名事例", "源点位名事例", "源轴名事例", "目标工站名事例", "目标点位名事例");
                Save(path);
            }
        }
        public static void Save(string path = "")
        {
            path = path == "" ? path = "..\\_Updata\\点位坐标关联配置.xml" : path;
            AccessXmlSerializer.ObjectToXml(path, _UpdataStationPointDatas);
        }
        public delegate void UpdatePointGridViewHander(string stationName, string PointName, int AxisColNum, double dCorrVal,bool bSave=true);
        public static UpdatePointGridViewHander eventUpdatePointGridView;
        public static void  UpdatePointData(UIDataGridView stcuIDataGridView,  string strSrcStationName, string strSrcPointName, PointInfo pointInfo,bool bSave=true)
        {
            List<UpdataStationPointData> SelDstPoints = _UpdataStationPointDatas.Where((t) => { return t.srcStationName == strSrcStationName && t.srcPointName == strSrcPointName; })?.ToList<UpdataStationPointData>();
            if (SelDstPoints == null || SelDstPoints.Count == 0)
                return ;
            for (int i = 0; i < SelDstPoints.Count; i++)
            {
                UpdataStationPointData pointdata = SelDstPoints[i];
                //源轴
                int nAxis = MotionMgr.GetInstace().GetAxisNoByName(pointdata.srcAxisName);
                //源工站
                Stationbase sb = StationMgr.GetInstance().GetStation(pointdata.srcStationName);
                if (sb.AxisX == nAxis && nAxis > -1)
                {
                    eventUpdatePointGridView?.Invoke(pointdata.dstStationName, pointdata.dstPointName, 1, pointInfo.pointX, bSave/*pointdata.dstStationName != pointdata.srcStationName*/);
                }
               else if (sb.AxisY == nAxis && nAxis > -1)
                {
                    eventUpdatePointGridView?.Invoke(pointdata.dstStationName, pointdata.dstPointName, 2, pointInfo.pointY, bSave/*pointdata.dstStationName != pointdata.srcStationName*/);
                }
                else if (sb.AxisZ == nAxis && nAxis > -1)
                {
                    eventUpdatePointGridView?.Invoke(pointdata.dstStationName, pointdata.dstPointName, 3, pointInfo.pointZ, bSave/*pointdata.dstStationName != pointdata.srcStationName*/);
                }
                else if (sb.AxisU == nAxis && nAxis > -1)
                {
                    eventUpdatePointGridView?.Invoke(pointdata.dstStationName, pointdata.dstPointName, 4, pointInfo.pointU, bSave/*pointdata.dstStationName != pointdata.srcStationName*/);
                }
                else if (sb.AxisTx == nAxis && nAxis > -1)
                {
                    eventUpdatePointGridView?.Invoke(pointdata.dstStationName, pointdata.dstPointName, 5, pointInfo.pointTx, bSave/*pointdata.dstStationName != pointdata.srcStationName*/);
                }
                else if (sb.AxisTy == nAxis && nAxis > -1)
                {
                    eventUpdatePointGridView?.Invoke(pointdata.dstStationName, pointdata.dstPointName, 6, pointInfo.pointTy, bSave/*pointdata.dstStationName != pointdata.srcStationName*/);
                    break;
                }
            }

        }

    }


    enum RowName
    {
        X = 0,
        Y = 1,
        Z = 2,
        U = 3,
        Tx = 4,
        Ty = 5
    }

}